package com.zhuoyue.web.controller.system;

import com.zhuoyue.common.annotation.Log;
import com.zhuoyue.common.core.controller.BaseController;
import com.zhuoyue.common.core.domain.AjaxResult;
import com.zhuoyue.common.core.domain.entity.SysDictData;
import com.zhuoyue.common.core.domain.entity.SysThirdData;
import com.zhuoyue.common.core.domain.entity.SysUser;
import com.zhuoyue.common.core.page.TableDataInfo;
import com.zhuoyue.common.enums.BusinessType;
import com.zhuoyue.common.utils.DealLogUtils;
import com.zhuoyue.common.utils.ServletUtils;
import com.zhuoyue.common.utils.StringUtils;
import com.zhuoyue.system.mapper.SysDictDataMapper;
import com.zhuoyue.system.mapper.SysThirdDataMapper;
import com.zhuoyue.web.utils.OrgCodeUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotBlank;
import java.util.Collections;
import java.util.List;

/**
 * @author wjming
 */
@RestController
@RequestMapping("/system/EzViz/device")
public class EzVizController extends BaseController {
    @Autowired
    private OrgCodeUtils orgCodeUtils;

    @Autowired
    private DealLogUtils dealLogUtils;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private SysThirdDataMapper sysThirdDataMapper;

    @GetMapping
    public TableDataInfo getDeviceList(Integer pageNum, Integer pageSize, String orgCode) {
        String ezToken = getEzToken(orgCode);
        if (StringUtils.isEmpty(ezToken)) {
            return new TableDataInfo(Collections.emptyList(), 0);
        }
        pageNum = pageNum - 1;
        String userUrl = "https://open.ys7.com/api/lapp/device/list?accessToken=" + ezToken
                + "&pageStart=" + pageNum + "&pageSize=" + pageSize;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<EzVizResult> forEntity = restTemplate.postForEntity(userUrl, null, EzVizResult.class);
        EzVizResult body = forEntity.getBody();
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setRows((List<?>) body.getData());
        dataInfo.setCode(200);
        dataInfo.setTotal(body.getPage().getTotal());
        return dataInfo;
    }


    @GetMapping("/info")
    public AjaxResult getDeviceInfo(@NotBlank(message = "组织编码不能为空") String orgCode,
                                    @NotBlank(message = "序列号不能为空") String deviceSerial) {
        String ezToken = getEzToken(orgCode);
        if (StringUtils.isEmpty(ezToken)) {
            return AjaxResult.error();
        }
        String deviceSerialUp = StringUtils.upperCase(deviceSerial);
        String userUrl = "https://open.ys7.com/api/lapp/device/info?accessToken="
                + ezToken + "&deviceSerial=" + deviceSerialUp;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<EzVizResult> forEntity = restTemplate.postForEntity(userUrl, null, EzVizResult.class);
        EzVizResult body = forEntity.getBody();
        return AjaxResult.success(body.getData());
    }


    @DeleteMapping
    @Log(title = "删除摄像头", businessType = BusinessType.DELETE)
    public AjaxResult removeDevice(@NotBlank(message = "组织编码不能为空") String orgCode,
                                   @NotBlank(message = "序列号不能为空") String deviceSerial) {
        String classAndMethodName = this.getClass().getName() + "." + "removeDevice()";
        SysUser user = orgCodeUtils.getLoginUser(ServletUtils.getRequest()).getUser();
        String ezToken = getEzToken(orgCode);
        if (StringUtils.isEmpty(ezToken)) {
            return AjaxResult.error();
        }
        AjaxResult deviceInfo = getDeviceInfo(orgCode, deviceSerial);
        dealLogUtils.setRedisSourceAndTargetData(classAndMethodName, user, deviceInfo.get(AjaxResult.DATA_TAG), null);

        String userUrl = "https://open.ys7.com/api/lapp/device/delete?accessToken="
                + ezToken + "&deviceSerial=" + deviceSerial;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<EzVizResult> forEntity = restTemplate.postForEntity(userUrl, null, EzVizResult.class);
        EzVizResult body = forEntity.getBody();
        return AjaxResult.success(body.getData());
    }

    @GetMapping("/getEzvizThirdData")
    public AjaxResult getEzvizThirdData(Long deptId) {
        SysDictData dictData = sysDictDataMapper.getEzvizDictData();
        SysThirdData ezvizData = sysThirdDataMapper.getThirdDataByDeptId(dictData.getDictCode(), deptId);
        SysThirdData resultData = new SysThirdData();
        if (ezvizData != null) {
            resultData.setCompanyMobile(ezvizData.getCompanyMobile());
        }
        return AjaxResult.success(resultData);
    }


    private String getEzToken(String orgCode) {
        String userUrl = "https://api.zyzncloud.com/third/api/ezvizUser/token/get?orgCode=" + orgCode;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<ControllerResult> forEntity = restTemplate.getForEntity(userUrl, ControllerResult.class);

        ControllerResult body = forEntity.getBody();
        if (!body.isSuccess()) {
            return null;
        }
        String dataObject = body.getDataObject().toString();
        String[] s = StringUtils.split(dataObject, "&");
        return s[0];
    }
}


/**
 * 萤石结果回传
 */
@Data
class EzVizResult {
    /**
     * 萤石回传信息
     */
    private String msg;
    /**
     * 编号
     */
    private String code;
    /**
     * 数据列表
     */
    private Object data;
    /**
     * 分页
     */
    private Page page;
}

/**
 * 分页
 */
@Data
class Page {
    /**
     * 总条数
     */
    private Long total;
    /**
     * 数据条数
     */
    private Integer size;
    /**
     * 页数
     */
    private Integer page;
}

@Data
class ControllerResult {
    /**
     * 操作结果标志
     */
    private boolean success;

    /**
     * 返回信息
     */
    private String msg;

    /**
     * 返回对象
     */
    private Object dataObject;

    /**
     * 消息code
     */
    private String msgCode;

}
